// 将秒转化为时分秒
export const handleSecondsToHms = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  return [hours, minutes, secs]
    .map((num) => (num < 10 ? '0' + num : num.toString()))
    .filter((str) => str)
    .join(':')
}

/**
 * 处理因为流内部的缓冲机制造成的，某个情况下会一次性返回多个数据块
 * 处理方案：根据 {} 切割，然后每一处尝试去用json.parse解构
 * @param text 流数据
 */
export const handleReadProcess = (text: string) => {
  const response: any[] = []

  if (!text) {
    return response
  }

  // 搜集 {} 的位置
  const indices = []
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '{' || text[i] === '}') {
      indices.push(i)
    }
  }

  let startIndex = null
  for (let i = 0; i < indices.length; i++) {
    if (startIndex == null && text[indices[i]] == '{') {
      startIndex = indices[i]
    } else {
      try {
        // 尝试解构
        const _text = text.substring(startIndex || 0, indices[i] + 1)
        const data = JSON.parse(_text)

        // 解构成功证明数据有效
        startIndex = null
        response.push(data)
      } catch {
        continue
      }
    }
  }

  return response
}

// 复制函数
export const handleCopyToClipboard = (text: string) => {
  if (navigator.clipboard) {
    // 现代浏览器支持的方法
    return navigator.clipboard.writeText(text)
  } else {
    // 对于不支持 navigator.clipboard 的浏览器
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    try {
      const successful = document.execCommand('copy')
      if (successful) {
        return Promise.resolve()
      } else {
        return Promise.reject(new Error('复制失败'))
      }
    } catch (err) {
      return Promise.reject(err)
    } finally {
      document.body.removeChild(textarea)
    }
  }
}
